package picol.model.asa.inst;

import java.util.ArrayList;
import java.util.List;
import picol.model.asa.ASAVariable;
import picol.model.asa.expr.ASAExpr;
import picol.model.memory.TableSymbole;

/**
 * Classe de gestion du programme PicoL
 * @author Aurélien Marcel - Julien Sanderson
 */
public class ASAInstPicoL extends ASAInst {

    public static List<TableSymbole> listTblSym = new ArrayList<TableSymbole>();
    private List<ASAInst> listInst;
    private int instIncr;
    private int listSize;

    public ASAInstPicoL() {
        this.listInst = new ArrayList<ASAInst>();
        this.instIncr = 0;
        this.addBloc();
    }

    public static void addVariable(ASAVariable _variable) {
        TableSymbole table = listTblSym.iterator().next();
        if (!table.existeVariable(_variable.getDeclaration().getIdent())) {
            table.nouvelleVariable(_variable);
        } else {
            throw new RuntimeException("Variable already declared");
        }
    }

    public void setListSize(int _listSize) {
        this.listSize = _listSize;
    }

    public void addBloc() {
        TableSymbole tblSym = new TableSymbole();
        listTblSym.add(tblSym);
    }

    public void add(ASAInst _inst) {
        this.listInst.add(_inst);
    }

    @Override
    public void executer() {
        for (ASAInst inst : this.listInst) {
            inst.executer();
        }
    }

    public boolean executerDebug() {
        if (this.instIncr < this.listSize) {
            this.listInst.get(instIncr++).executerDebug();
        } else {
            return true;
        }
        return false;
    }

    public int getInstIncr() {
        return this.instIncr;
    }

    public String getVarList() {
        String string = "";
        for (TableSymbole tbl : listTblSym) {
            string += tbl.toString();
        }
        return string;
    }

    public static void modifierVar(String ident, ASAExpr evalue) {
        for (TableSymbole tblSymb : listTblSym) {
            if (tblSymb.existeVariable(ident)) {
                tblSymb.modifierVariable(ident, evalue);
                break;
            }
        }
    }

    public static void resetTableSymbole() {
        listTblSym = new ArrayList<TableSymbole>();
    }

    @Override
    public int getNbInst() {
        int nbinst = 0;
        for (ASAInst inst : listInst) {
            nbinst += inst.getNbInst();
            nbinst++;
        }
        return nbinst;
    }
}
